//
//  JUFNWelcomeVController.swift
//  WiBoPM
//
//  Created by 陈俊峰 on 2017/1/8.
//  Copyright © 2017年 陈俊峰. All rights reserved.
/*

 实现一个头像和一个label的动画效果
 总结:不能将动画放在viewWillAppear中,因为是先执行顺序是viewdidLoad->viewWillAppear->viewWillLayoutSbuviews->viewDidLayoutSubViews ->viewDidAppear,在viewDidLayoutSubViews之后才会给控件分配frame
 */

import UIKit
import SDWebImage

private let iconWidth = 90
private let offsetY = 120
private let marginY = 20
class JUFNWelcomeVController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }

    func setupUI() {
        view.backgroundColor = UIColor.white
        view.addSubview(iconImage)
        view.addSubview(welcomeLab)
        iconImage.layer.cornerRadius = 45
        iconImage.layer.masksToBounds = true
        iconImage.sd_setImage(with: JUFNAuthorViewModel.shared.avatarUrl)
        
        welcomeLab.alpha = 0
        //设置约束
        iconImage.snp.makeConstraints { (make) in
            make.width.height.equalTo(iconWidth)
            make.centerX.equalTo(view)
            make.bottom.equalTo(view).offset(-offsetY)
        }
        welcomeLab.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(iconImage.snp.bottom).offset(marginY)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //这里更新约束,并添加动画
        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: [], animations: {
            self.iconImage.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY + iconWidth - Int(screenHeight))
            })
             self.view.layoutIfNeeded()
        }) { (completed) in
            UIView.animate(withDuration: 0.5, delay: 0, options: [], animations: {
                self.welcomeLab.alpha = 1
            }, completion: { (completed) in
                NotificationCenter.default.post(name: .ChangeRootViewController, object: "JUFNMainViewController")
                
            })
        }
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    //头像图片
    lazy var iconImage : UIImageView = UIImageView(image: #imageLiteral(resourceName: "avatar_default_big"))
    
    //label
    lazy var welcomeLab :UILabel = UILabel(text: ((JUFNAuthorViewModel.shared.userAcc?.screen_name) ?? "") + "欢迎回来", fontSize: 14, textColor: UIColor.black)
}
